package pers.wk.queues.dlx;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列消费者
 */
@Slf4j
public class DlxConsumer {

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();
            //4.声明正常交换机
            channel.exchangeDeclare(MQConfig.ExchangeName.DLX_EXCHANGE, MQConfig.ExchangeType.direct);

            channel.queueDeclare(MQConfig.QueueNames.DLX_QUEUE, false, false, false, null);

            //队列绑定交换机
            String routingKey = "error";
            channel.queueBind(MQConfig.QueueNames.DLX_QUEUE, MQConfig.ExchangeName.DLX_EXCHANGE, routingKey);
            System.out.println("死信队列消费者启动。。。");

            Channel channelTemp = channel;
            channelTemp.basicConsume(MQConfig.QueueNames.DLX_QUEUE, true, (consumerTag, message) -> {
                //@FunctionalInterface DeliverCallback
                System.out.println(MessageFormat.format("死信队列消费者获取消息：【{1}】{0}",
                        new String(message.getBody(), "UTF-8")
                        , message.getEnvelope().getDeliveryTag()));
            }, (consumerTag) -> {
                //@FunctionalInterface CancelCallback
            });

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MQConnectionUtils.close(connection, channel);
        }
    }
}
